﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Collections;

namespace PersonaLibrary.ViewModel
{
    public class FilteredCollectionViewModel<T> : OrderByCollection<T>
        where T : DataModel.Entity
    {
        private string filteredPropertyName;
        private object filteredPropertyValue;
        private IEnumerable filterSource;

        public FilteredCollectionViewModel()
             : base()
        { }

        public string FilteredPropertyName
        {
            get
            {
                return filteredPropertyName;
            }
            set
            {
                filteredPropertyName = value;
                risePropertyChanged("FilteredPropertyName");
                if (filteredPropertyValue != null)
                {
                    OnFilterChanged();
                }
            }
        }

        public object FilteredPropertyValue
        {
            get
            {
                return filteredPropertyValue;
            }
            set
            {
                filteredPropertyValue = value;
                risePropertyChanged("FilteredPropertyValue");
                if (!string.IsNullOrEmpty(filteredPropertyName))
                {
                    OnFilterChanged();
                }
            }
        }

        public IEnumerable ItemFilterSource
        {
            get
            {
                return filterSource;
            }
            protected set
            {
                filterSource = value;
                risePropertyChanged("FilterSource");
            }
        }

        protected virtual void OnFilterChanged()
        {
            Refresh();
        }

        public virtual Func<T, bool> Filter
        {
            get
            {
                if (!string.IsNullOrEmpty(FilteredPropertyName) && filteredPropertyValue != null)
                {
                    return x => x.GetType().GetProperty(FilteredPropertyName).GetValue(x, null) == filteredPropertyValue;
                }
                else return x => true;
            }
        }

        protected override void OnOrderByChanged()
        {
            
        }

        public override void Refresh()
        {
            IsEditable = false;
            Collection.LoadCondition = Filter;
            Collection.LoadComplite += delegate
            {
                IsEditable = true;
                Collection.AsQueryable().OrderBy(OrderExpression);                
            };
            Collection.Load();
            risePropertyChanged("Collection");
        }
    }
}
